package com.mizhiquan.util;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.GetObjectRequest;
import com.mizhiquan.common.Const;

import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.File;

/**
 * Created by Shane on 2017/6/25.
 */
public class UploadToOssUtil {



    /**
     * 通过bufferdInput流上传到oss中，key为路径
     * @param key
     * @param in
     */
    public void UpToOss(String key, BufferedInputStream in, Const.BucketName bucketName){
        OSSClient ossClient = new OSSClient(Const.ENDPOINT,Const.accessKeyId, Const.accessKeySecret);
        ossClient.putObject(bucketName.getValue(), key, in);
        ossClient.shutdown();
    }

    /**
     * 通过文件流上传到oss中，key为路径
     * @param key
     * @param in
     */
    public void UpToOss(String key,File in , Const.BucketName bucketName){
        OSSClient ossClient = new OSSClient(Const.ENDPOINT,Const.accessKeyId, Const.accessKeySecret);
        ossClient.putObject(bucketName.getValue(), key, in);
        ossClient.shutdown();
    }

    /**
     * 通过byte数组上传到oss中，key为路径
     * @param key
     * @param b
     */

    public void UpToOss(String key,byte[] b , Const.BucketName bucketName){
        OSSClient ossClient = new OSSClient(Const.ENDPOINT,Const.accessKeyId, Const.accessKeySecret);
        ossClient.putObject(bucketName.getValue(), key,  new ByteArrayInputStream(b));
        ossClient.shutdown();
    }

    /**
     * 从oss中删除key的文件
     * @param key
     */
    public void DeleteFromOss(String key , Const.BucketName bucketName){
        OSSClient ossClient = new OSSClient(Const.ENDPOINT,Const.accessKeyId, Const.accessKeySecret);
        ossClient.deleteObject(bucketName.getValue(), key);
        ossClient.shutdown();
    }

    /**
     * 从oss中下载key的文件到loc地址
     * @param key
     * @param loc
     */
    public void GetOss(String key,String loc , Const.BucketName bucketName){
        OSSClient ossClient = new OSSClient(Const.ENDPOINT, Const.accessKeyId, Const.accessKeySecret);
        //从bucket中获取到文件下载到loc路径
        ossClient.getObject(new GetObjectRequest(bucketName.getValue(), key), new File(loc));
        ossClient.shutdown();
    }

}
